import React, { useState, useContext, useEffect } from "react";

const UserContext = React.createContext();

const { Provider, Consumer } = UserContext;

// console.log(UserContext);

function Context() {
  const [name, setName] = useState("Leo");

  useEffect(() => {
    setTimeout(() => setName("Frank"), 1000);
  }, []);

  const logout = () => {
    setName("");
  };

  return (
    <>
      <Provider value={{ name, logout }}>
        <div>Context Father组件</div>
        <Consumer>{(value) => <div>{value.name}</div>}</Consumer>
        {/* <Consumer>{(value) => <div>{value.name}</div>}</Consumer> */}
        <Children />
      </Provider>
    </>
  );
}

function Children() {
  // 惯用解构赋值
  const { name, logout } = useContext(UserContext);
  return (
    <>
      <h3>Son组件</h3>
      <div>{name}</div>
      <button onClick={logout}>注销</button>
    </>
  );
}

export default Context;
